#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Denis Kürov
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt.

from django import newforms as forms
from firefield import PortField,IpTableForm,IpDropField,IpDropWidget,IpLoadField,IpLoadWidget,\
MacField,PortMultiField,PortWidget,PaketLimitField,MyChainField
from fireutil import FireUtils
from iptables.models import Chain,Target
import re


class IpDropForm(forms.Form):
    """The real ip form with its validation and all stuff"""
    
    name=forms.CharField(max_length=20)
    zincir=forms.ChoiceField(widget=forms.Select(attrs=
                                                 {"onchange":"dev_disable(document.getElementsByName(\"zincir\"),\
                                                  document.getElementsByName(\"kaynak_aygit\"),\
                                                  document.getElementsByName(\"hedef_aygit\"))"}))
    eylem=forms.ChoiceField()
    
    kaynak_ip=IpDropField(widget=IpDropWidget(attrs={'ip':'s'}))
    hedef_ip=IpDropField(widget=IpDropWidget(attrs={'ip':'d'}))
    
    kaynak_aygit=forms.ChoiceField(initial="eth0")
    hedef_aygit=forms.ChoiceField(initial="eth0")
    
    yukle=IpLoadField(widget=IpLoadWidget)
    
    def __init__(self,*args,**kwargs):
        """ The updated parts .."""
        super(IpDropForm, self).__init__(*args, **kwargs)
        dev_sec=FireUtils.active_device()
        
        self.fields['kaynak_aygit'].choices=dev_sec
        self.fields['hedef_aygit'].choices=dev_sec
        
        self.fields['eylem'].choices=[(i.id, i.name) for i in Target.objects.all()]
        self.fields['zincir'].choices=[(i.id, i.name) for i in Chain.objects.all()]
        
        #that parts are for loaded rule really hacking :)
        
        self.fields['yukle'].fields[0].choices=FireUtils.get_loaded_rules()
        self.fields['yukle'].widget.widgets[0].choices=FireUtils.get_loaded_rules()
        
class UdpForm(forms.Form):
    """ The udp form for adding and editing the rulez"""
    #the ports
    kaynak_port=PortMultiField(widget=PortWidget(attrs={'port':'s'}))
    hedef_port=PortMultiField(widget=PortWidget(attrs={'port':'d'}))

flag_choices=(
              ('ALL','ALL'),
              ('SYN','SYN'),
              ('ACK','ACK'),
              ('FIN','FIN'),
              ('RST','RST'),
              ('URG','URG'),
              ('PSH','PSH'),
              ('NONE','NONE'),
              )

class TcpForm(UdpForm):
    """ Inherits from previous one to skip the code rewriting"""
    def __init__(self,*args,**kwargs):
        """ Call the one we inherited from"""
        super(TcpForm, self).__init__(*args, **kwargs)
        
    seter=forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'size':'8'}),required=False,choices=flag_choices)
    comparer=forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'size':'8'}),required=False,choices=flag_choices)

takip_choices=(
               ('INVALID','INVALID'),
               ('ESTABLISHED','ESTABLISHED'),
               ('NEW','NEW'),
               ('RELATED','RELATED'),
               
               )

durum_choices=(
               ('NONE','NONE'),
               ('ASSURED','ASSURED'),
               ('EXPECTED','EXPECTED'),
               ('SEEN_REPLY','SEEN_REPLY'),
               
                )

d_limit_choices=(
                 ('second','saniye'),
                 ('minute','dakika'),
                 ('hour','saat'),
                 ('day','gun'),
                 )

class ExtraForm(forms.Form):
    """ That one is m options of Models"""
    #baglanti takip cotstatus
    b_takip=forms.MultipleChoiceField(widget=forms.SelectMultiple(),required=False,choices=takip_choices)
    b_takip_c=forms.BooleanField(required=False)
    
    #baglanti durum ctstate
    b_durum=forms.MultipleChoiceField(widget=forms.SelectMultiple(),required=False,choices=durum_choices)
    b_durum_c=forms.BooleanField(required=False)
    
    #paket limit koyma make it custom yani
    p_limit=PaketLimitField(max_length=10,required=False)
    p_limit_c=forms.BooleanField(required=False)
    
    #durum limiti koyma bu dos ataklar ve vs logda kullanilir limit bisi bisi
    limit=forms.IntegerField(required=False)
    d_limit_select=forms.ChoiceField(choices=d_limit_choices)
    burst=forms.IntegerField(required=False)
    
    #bir de mac sinirlamasi getirelim
    mac=MacField(required=False)
    mac_c=forms.BooleanField(required=False)
    
icmp_choices=(
                ('any','any'),
                ('echo-reply','echo-reply'),
                ('destination-unreachable','destination-unreachable'),
                ('network-unreachable','network-unreachable'),
                ('host-unreachable','host-unreachable'),
                ('protocol-unreachable','protocol-unreachable'),
                ('port-unreachable','port-unreachable'),
                ('fragmentation-needed','fragmentation-needed'),
                ('source-route-failed','source-route-failed'),
                ('network-unknown','network-unknown'),
                ('host-unknown','host-unknown'),
                ('network-prohibited','network-prohibited'),
                ('host-prohibited','host-prohibited'),
                ('TOS-network-unreachable','TOS-network-unreachable'),
                ('TOS-host-unreachable','TOS-host-unreachable'),
                ('communication-prohibited','communication-prohibited'),
                ('host-precedence-violation','host-precedence-violation'),
                ('precedence-cutoff','precedence-cutoff'),
                ('source-quench','source-quench'),
                ('redirect','redirect'),
                ('network-redirect','network-redirect'),
                ('host-redirect','host-redirect'),
                ('TOS-network-redirect','TOS-network-redirect'),
                ('TOS-host-redirect','TOS-host-redirect'),
                ('echo-request','echo-request'),
                ('router-advertisement','router-advertisement'),
                ('router-solicitation','router-solicitation'),
                ('time-exceeded','time-exceeded'),
                ('ttl-zero-during-transit','ttl-zero-during-transit'),
                ('ttl-zero-during-reassembly','ttl-zero-during-reassembly'),
                ('parameter-problem','parameter-problem'),
                ('ip-header-bad','ip-header-bad'),
                ('required-option-missing','required-option-missing'),
                ('timestamp-request','timestamp-request'),
                ('timestamp-reply','timestamp-reply'),
                ('address-mask-request','address-mask-request'),
                ('address-mask-reply','address-mask-reply'),
    )

class IcmpForm(forms.Form):
    """ The icmp option is for that one"""
    icm_tip=forms.ChoiceField(choices=icmp_choices,initial='any')
    icmp_c=forms.BooleanField(required=False)
    
class PrefixForm(forms.Form):
    """ Entering the log word for the current rule"""
    log_adi=forms.CharField(max_length=29)
    
log_choices=(
                 ('p','Prefix'),
                 ('sp','Kaynak Port'),
                 ('dp','Hedef Port'),
                 ('si','Kaynak Ip'),
                 ('di','Hedef Ip'),
                 ('sd','Kaynak Aygit'),
                 ('dd','Hedef Aygit'),
            )

kelime_re=re.compile(r'(^\w+$)|(^\d{1,5}|\.$)')

class LogSearchForm(forms.Form):
    """ That one is a filter form for LOgs to be displayed in different 
    aspects..."""

    kelime=forms.RegexField(regex=kelime_re,max_length=29,required=False,error_message="Yanlis arama kriteri")
    kriter=forms.ChoiceField(choices=log_choices,initial='p')
    
class ChainForm(forms.Form):
    """That one is for adding and editing chains """
    
    isim = MyChainField(max_length=29)
    aciklama= forms.CharField(max_length=50,widget=forms.Textarea())
    
